import type { Context } from 'elysia';
import { eq, desc, asc, and } from 'drizzle-orm';
import { db } from '../db';
import { productProcesses, processParameters } from '../db/schema';
import { nanoid } from 'nanoid';
import { successResponse, errorResponse, ApiError, asyncHandler, Logger } from '../utils/response';
import type { AuthContext } from '../middleware/auth';

// 获取产品工艺列表
export const getProductProcesses = asyncHandler(async ({ query, set }: Context) => {
    const { productId, status = 'active' } = query as any;

    const conditions = [];
    
    if (productId) {
      conditions.push(eq(productProcesses.productId, productId));
    }
    
    if (status) {
      conditions.push(eq(productProcesses.status, status));
    }

    const whereClause = conditions.length > 0 ? and(...conditions) : undefined;

    const processes = await db.select()
      .from(productProcesses)
      .where(whereClause)
      .orderBy(asc(productProcesses.sort), asc(productProcesses.createdAt));

    Logger.info('获取产品工艺列表', { 
      processesCount: processes.length, 
      productId: productId || 'all'
    });

    return successResponse(processes, '获取产品工艺列表成功');
});

// 获取单个产品工艺（包含参数）
export const getProductProcess = asyncHandler(async ({ params, set }: Context) => {
    const { id } = params as { id: string };
    
    const processResult = await db.select()
      .from(productProcesses)
      .where(eq(productProcesses.id, id))
      .limit(1);
    
    const process = processResult[0];
    
    if (!process) {
      throw ApiError.notFound('产品工艺不存在');
    }

    // 获取工艺参数
    const specifications = await db.select()
      .from(processParameters)
      .where(eq(processParameters.processId, id))
      .orderBy(asc(processParameters.sort));

    const processWithSpecs = {
      ...process,
      specifications
    };

    Logger.info('获取产品工艺详情', { processId: id, processName: process.name });

    return successResponse(processWithSpecs, '获取产品工艺详情成功');
});

// 创建产品工艺
export const createProductProcess = asyncHandler(async ({ body, set }: AuthContext) => {
    const {
      productId,
      name,
      description,
      image,
      sort = 0,
      status = 'active',
      specifications = []
    } = body as any;

    if (!productId || !name) {
      throw ApiError.validation('产品ID和工艺名称为必填项');
    }

    const processData = {
      id: nanoid(),
      productId,
      name,
      description,
      image,
      sort: parseInt(sort) || 0,
      status
    };

    const [newProcess] = await db.insert(productProcesses).values(processData).returning();

    // 创建工艺参数
    if (specifications && specifications.length > 0) {
      const specData = specifications.map((spec: any, index: number) => ({
        id: nanoid(),
        processId: newProcess.id,
        name: spec.name,
        value: spec.value,
        unit: spec.unit,
        sort: spec.sort || index
      }));

      await db.insert(processParameters).values(specData);
    }

    Logger.info('创建产品工艺', { processId: newProcess.id, processName: name, productId });

    return successResponse(newProcess, '产品工艺创建成功');
});

// 更新产品工艺
export const updateProductProcess = asyncHandler(async ({ params, body, set }: AuthContext) => {
    const { id } = params as { id: string };
    const {
      name,
      description,
      image,
      sort,
      status,
      specifications
    } = body as any;

    // 检查工艺是否存在
    const existingProcess = await db.select()
      .from(productProcesses)
      .where(eq(productProcesses.id, id))
      .limit(1);

    if (existingProcess.length === 0) {
      throw ApiError.notFound('产品工艺不存在');
    }

    const updateData: any = {};
    
    if (name !== undefined) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (image !== undefined) updateData.image = image;
    if (sort !== undefined) updateData.sort = parseInt(sort);
    if (status !== undefined) updateData.status = status;

    const [updatedProcess] = await db.update(productProcesses)
      .set(updateData)
      .where(eq(productProcesses.id, id))
      .returning();

    // 更新工艺参数
    if (specifications !== undefined) {
      // 删除现有参数
      await db.delete(processParameters).where(eq(processParameters.processId, id));
      
      // 创建新参数
      if (specifications.length > 0) {
        const specData = specifications.map((spec: any, index: number) => ({
          id: nanoid(),
          processId: id,
          name: spec.name,
          value: spec.value,
          unit: spec.unit,
          sort: spec.sort || index
        }));

        await db.insert(processParameters).values(specData);
      }
    }

    Logger.info('更新产品工艺', { processId: id, updatedFields: Object.keys(updateData).length });

    return successResponse(updatedProcess, '产品工艺更新成功');
});

// 删除产品工艺
export const deleteProductProcess = asyncHandler(async ({ params, set }: AuthContext) => {
    const { id } = params as { id: string };

    // 检查工艺是否存在
    const existingProcess = await db.select()
      .from(productProcesses)
      .where(eq(productProcesses.id, id))
      .limit(1);

    if (existingProcess.length === 0) {
      throw ApiError.notFound('产品工艺不存在');
    }

    // 删除工艺参数
    await db.delete(processParameters).where(eq(processParameters.processId, id));
    
    // 删除工艺
    await db.delete(productProcesses).where(eq(productProcesses.id, id));

    Logger.info('删除产品工艺', { processId: id, processName: existingProcess[0].name });

    return successResponse(null, '产品工艺删除成功');
});

// 获取工艺参数列表
export const getProcessSpecifications = asyncHandler(async ({ query, set }: Context) => {
    const { processId } = query as any;

    if (!processId) {
      throw ApiError.validation('工艺ID为必填项');
    }

    const specifications = await db.select()
      .from(processParameters)
      .where(eq(processParameters.processId, processId))
      .orderBy(asc(processParameters.sort));

    Logger.info('获取工艺参数列表', { 
      specificationsCount: specifications.length, 
      processId 
    });

    return successResponse(specifications, '获取工艺参数列表成功');
});